/* eslint-disable no-console */
const rollup = require('rollup');
const path = require('path');
const chalk = require('chalk');
const constant = require('./constant');
const { getPlugins } = require('./rollup.plugin');
const utils = require('./utils');

/**
 * @param {string} dir
 */
function serve(dir) {
  const options = rollup.defineConfig({
    input: path.resolve(dir, 'src', 'index.ts'),
    output: {
      banner: constant.BANNER,
      file: path.resolve(dir, 'public', 'main-dev.js'),
      sourcemap: true,
      format: 'esm',
    },
    plugins: getPlugins(dir, 'development'),
  });
  const watcher = rollup.watch(options);

  // const filename = options.output.file.replace(cwd, '');
  let timestamp = Date.now();
  watcher.on('event', (e) => {
    if (e.code === 'START') {
      console.clear();
      console.log(chalk.underline(`rollup ${rollup.VERSION}`));
    }
    if (e.code === 'BUNDLE_START') {
      let input;
      if (typeof e.input === 'string') {
        input = e.input;
      } else if (Array.isArray(e.input)) {
        input = e.input.join(',');
      } else {
        input = Object.values(e.input).join(',');
      }
      console.log(
        chalk.cyan('bundles'),
        chalk.bold.cyan(`${input} => ${e.output.map(utils.relativeId).join(',')}`),
      );
      timestamp = Date.now();
    }
    if (e.code === 'BUNDLE_END') {
      const output = e.output.map(utils.relativeId).join(',');
      console.log(
        chalk.green('created'),
        chalk.bold.cyan(output),
      );
    }
    if (e.code === 'END') {
      const date = new Date();
      console.log(`\n[COMPILER] ${date.getTime() - timestamp} ms`);
      console.log(`[${utils.formatDate(date)}] waiting for changes...`);
    }
    if (e.code === 'ERROR') {
      console.log(chalk.red('build failed', e.error.message, '\n', e.error.id));
    }
  });
}

const root = utils.resolve('');
serve(root);
